package com.tools.api;


import cn.hutool.core.codec.Base64Encoder;
import com.tools.commons.constants.SystemConstants;
import com.tools.commons.exceptions.BadRequestException;
import com.tools.model.Request.ResultRequest;
import com.tools.model.Request.listUserRequest;
import com.tools.model.entity.*;
import com.tools.model.params.PicsParams;
import com.tools.security.context.SecurityContext;
import com.tools.security.context.SecurityContextHolder;
import com.tools.security.context.UserInfo;
import com.tools.service.*;
import com.tools.utils.HttpClientUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javassist.bytecode.stackmap.BasicBlock;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

@RestController
@RequiredArgsConstructor
@Api(tags = "user-Conttroller")
@RequestMapping(SystemConstants.Api.USER)
public class UserController {
    private final UserService userService;
    private final UserTaskSerive userTaskSerive;
    private final UserMsgsService userMsgsService;
    private final UserUpLoadService userUpLoadService;
    private final ResultService resultService;

    @GetMapping("info")
    @ApiOperation("查看当前用户信息")
    public UserInfo userInfo() {
        SecurityContext context = SecurityContextHolder.getContext();
        return context.getUserInfo();
    }

    @GetMapping("userList")
    @ApiOperation("病人列表")
    public List<listUserRequest> userList() {
        return userService.listAll(false);
    }

    //手机号找病人
    @GetMapping("findUserByPhone")
    @ApiOperation("手机号找病人")
    public UserEntity findUserByPhone(String phone) {
        return userService.loginInPhone(phone, false);
    }

    @GetMapping("taskListByUserId")
    @ApiOperation("病人任务列表")
    public List<UserTasksEntity> getTaskListById() {
        return userTaskSerive.findTaskListByUserId(SecurityContextHolder.getContext().getUserInfo().getUserId());
    }

    @GetMapping("getMsgList")
    @ApiOperation("消息列表and已读某消息")
    public List<UserMsgRelEntity> getMsgListById() {
        return userMsgsService.findMsgListByUserId(SecurityContextHolder.getContext().getUserInfo().getUserId());
    }

    @PostMapping("notReadCount")
    @ApiOperation("未读消息个数")
    public int notReadCount() {
        return userMsgsService.noReadNum(SecurityContextHolder.getContext().getUserInfo().getUserId());
    }

    @PostMapping("analysis")
    @ApiOperation("analysis")
/*
    public  void analysis(@RequestBody UserUploadPicEntity userUploadPicEntity){
        String headUrl="http://116.63.146.54:9856/get_eye_width?url=";
        String url ="http://pics.minggen.wang/";
        url = url +  userUploadPicEntity.getPic();
        byte[] token = DigestUtils.md5(url);
        token = Base64.getEncoder().encode(token);
        token = Base64.getEncoder().encode(token);
        token = DigestUtils.sha1(token);
        token = DigestUtils.sha1(token);
        token = DigestUtils.sha1(token);
        String sToken = Base64.getEncoder().encode(token).toString();
        url =headUrl+ url +"&token:"+token;

        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"utf-8"));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String str=json.toString();
        String date="000000000";
        if(str.indexOf("Success")!=-1){

            String[] buff = str.split("//}|:");
            date = buff[3];
        }
*/
    public void analysis(@RequestBody UserUploadPicEntity userUploadPicEntity) {
        String url = "http://pics.minggen.wang/";
        url = url + userUploadPicEntity.getPic();
        Optional<R> r = execute(url);
        ResultEntity resultEntity = new ResultEntity();
        try {
            String openDate = r.map(R::getFaces).filter(a->a.size()>0).map(a -> a.get(0)).map(Face::getM_e).orElse("0");
           if (openDate.equals("0")){
               throw new BadRequestException();
           }
            resultEntity.setOpenDate(openDate);
        }catch (Exception e){
            throw new BadRequestException("未检测到人脸,请在明亮处重新拍照");
        }

        resultEntity.setTaskUserId(userUploadPicEntity.getUserTaskId());
       resultEntity.setTaskUserId(userUploadPicEntity.getUserTaskId());
       resultEntity.setPic(userUploadPicEntity.getPic());
        resultService.save(resultEntity);
    }

    @PostMapping("saveTaskPics")
    @ApiOperation("上传图片")
    public void upLoadPic(@RequestBody @Validated PicsParams picsParams) {
        if (SecurityContextHolder.getContext().getUserInfo().isDoctor()) {
            throw new BadRequestException("无权限");
        }
        if (userTaskSerive.findByUserTaskId(picsParams.getUserTaskId()) == null) {
            throw new BadRequestException("无此任务");
        }
        UserUploadPicEntity userUploadPicEntity = userUpLoadService.save(picsParams);

        analysis(userUploadPicEntity);


    }

    @GetMapping("analysisResult")
    public ResultRequest analysisResult(String userTaskId) {
        return resultService.getResultByUserTaskId(userTaskId);
    }

    /*@Data
    public static class XOY implements Serializable {
        List<String> categories = Lists.newArrayList();
        List<Integer> data = Lists.newArrayList();

        public XOY(List<String> categories, List<Integer> data) {
            this.categories = categories;
            this.data = data;
        }

        public static XOY demo() {
            List<String> categories = Lists.newArrayList();
            List<Integer> data = Lists.newArrayList();

            for (int i = 0; i < 30; i++) {
                categories.add("1-" + (i + 1));
                data.add((int) (Math.random() * (20 - 10))+2);
            }
            return new XOY(categories, data);
        }
    }*/
    public static Optional<R> execute(String url) {
        R r = HttpClientUtil.post("http://47.100.248.211:9856/get_eye_width")
                .param("url", url)
                .param("token", token(url)).execute(R.class);
        return Optional.ofNullable(r);
    }

    public static String token(String url) {
        url = DigestUtils.md5Hex(url);
        url = Base64Encoder.encode(url.getBytes());
        url = Base64Encoder.encode(url.getBytes());
        url = DigestUtils.sha1Hex(url.getBytes());
        url = DigestUtils.sha1Hex(url.getBytes());
        url = DigestUtils.sha1Hex(url.getBytes());
        url = Base64Encoder.encode(url.getBytes());
        return url;
    }

    @Data
    public static class R implements Serializable {
        String message;
        List<Face> faces;
    }

    @Data
    public static class Face implements Serializable {
        String m_e;
    }
}
